package com.splant.android.smart.UILevel.Community.fragments;

import android.app.Fragment;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.github.jdsjlzx.ItemDecoration.GridItemDecoration;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.splant.android.R;
import com.splant.android.smart.CommunicationLevel.sPlantAsyncHttpClient;
import com.splant.android.smart.CommunicationLevel.sPlantJsonHttpResponseHandler;
import com.splant.android.smart.Global;
import com.splant.android.smart.ModelLevel.AreaListBean;
import com.splant.android.smart.ModelLevel.DetectorListBean;
import com.splant.android.smart.SystemDefinedLevel.Utils.System_Dimen_Util;
import com.splant.android.smart.UILevel.Community.Garden_Detector_Activity;
import org.apache.http.Header;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;

public class Garden_DetectorList_Fragment extends Fragment {

    private static final int REQUEST_COUNT = 8;
    private sPlantAsyncHttpClient sPlantClient;
    private View mView;
    private LRecyclerView lrv_detectorList;
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private Garden_DetectorList_Adapter garden_detectorList_adapter;
    private List<DetectorListBean.Detector> detectorList = new ArrayList<>();
    private TextView tv_areaName;
    private String areaId="";
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mView == null) {

            mView = inflater.inflate(R.layout.garden_detectorlist_fragment, null);

            lrv_detectorList = (LRecyclerView) mView.findViewById(R.id.lrv_detectorList);
            tv_areaName = (TextView) getActivity().findViewById(R.id.tv_areaName);
            sPlantClient = sPlantAsyncHttpClient.getInstance();

            init();


        }
        return mView;
    }

    private void init() {

        garden_detectorList_adapter = new Garden_DetectorList_Adapter(getActivity());
        lRecyclerViewAdapter = new LRecyclerViewAdapter(garden_detectorList_adapter);

        lrv_detectorList.setHasFixedSize(true);
        lrv_detectorList.setLayoutManager(new GridLayoutManager(getActivity(), 1));
        lrv_detectorList.setAdapter(lRecyclerViewAdapter);
        lrv_detectorList.setRefreshProgressStyle(ProgressStyle.BallClipRotateMultiple);

        GridItemDecoration divider = new GridItemDecoration.Builder(getActivity())
                .setVertical(R.dimen.gaiaa_devicelist_dh)
                .setColorResource(R.color.garden_color0)
                .build();

        lrv_detectorList.addItemDecoration(divider);

        lrv_detectorList.setFooterViewHint("拼命加载中","已经全部为你呈现了","网络不给力啊，点击再试一次吧");
        lrv_detectorList.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);

        lrv_detectorList.setOnRefreshListener(onRefreshListener);

        lrv_detectorList.setOnLoadMoreListener(onLoadMoreListener);

        garden_detectorList_adapter.setOnItemClickListener(new Garden_DetectorList_Adapter.onItemClickListener() {
            @Override
            public void onItemChick(int pos) {

                Intent intent = new Intent(getActivity(), Garden_Detector_Activity.class);

                intent.putExtra("detector", garden_detectorList_adapter.getDataList().get(pos));

                startActivity(intent);
            }
        });

        getDatas();
    }


    public void selectArea() {
        if (tv_areaName != null) {
            String curAreaName = tv_areaName.getText().toString();
            if (Global.selectedArea != null && curAreaName.equals("选择区域") == false && Global.selectedArea.getAreaId().equals(areaId) == false) {
                pageNo = 0;
                detectorList.clear();
                getDatas();
            }
        }
    }

    private void getDatas() {

        if (Global.user == null)
            return;

        RequestParams params = new RequestParams();
        params.put("userId", Global.user.getUserId());
        params.put("pageNo", pageNo);
        params.put("pageSize", REQUEST_COUNT);
        params.put("isAutoTimer", 0);

        if (Global.selectedArea != null && Global.selectedArea.getAreaId().equals("") == false)
            params.put("areaId", Global.selectedArea.getAreaId());

        lrv_detectorList.setNoMore(false);

        sPlantClient.get(sPlantAsyncHttpClient.GETDETECTORDEVICES, params, new sPlantJsonHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try {
                    if (response.getInt("succeed") == 1) {

                        Gson gson = new Gson();
                        DetectorListBean detectorListBean = gson.fromJson(response.toString(), DetectorListBean.class);

                        if (Global.selectedArea != null)
                            areaId = Global.selectedArea.getAreaId();

                        if (detectorListBean.getDetectorList() != null && detectorListBean.getDetectorList().size() > 0) {

                            if (detectorListBean.getDetectorList().size() < REQUEST_COUNT)
                                lrv_detectorList.setNoMore(true);

                        } else {
                            lrv_detectorList.setNoMore(true);
                        }

                        detectorList.addAll(detectorListBean.getDetectorList());
                        garden_detectorList_adapter.setDataList(detectorList);

                        lrv_detectorList.refreshComplete(REQUEST_COUNT);

                        if (detectorList.size() == 0)
                            Toast.makeText(getActivity(), "此区域内无检测器", Toast.LENGTH_LONG).show();
                    }

                } catch (Exception e) {
                    lrv_detectorList.refreshComplete(REQUEST_COUNT);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                lrv_detectorList.refreshComplete(REQUEST_COUNT);
                Toast.makeText(getContext(), getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();
            }
        });

    }

    private OnRefreshListener onRefreshListener = new OnRefreshListener() {
        @Override
        public void onRefresh() {

            pageNo = 0;
            detectorList.clear();
            getDatas();

        }
    };
    private int pageNo = 0;
    private OnLoadMoreListener onLoadMoreListener = new OnLoadMoreListener() {
        @Override
        public void onLoadMore() {

            if (Global.selectedArea == null || Global.selectedArea.getAreaId().equals("")) {
                pageNo += 1;
                getDatas();
            } else {
                lrv_detectorList.setNoMore(true);
            }

        }
    };

}
